package main

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"golang.org/x/text/encoding/charmap"
	"golang.org/x/text/transform"
	"io"
	"log"
	"net"
)

func from866(b []byte) string {
	reader := transform.NewReader(bytes.NewReader(b), charmap.CodePage866.NewDecoder())
	r, _ := io.ReadAll(reader)
	return string(r)
}

func to866(s string) []byte {
	buff := new(bytes.Buffer)
	writer := transform.NewWriter(buff, charmap.CodePage866.NewEncoder())
	defer writer.Close()
	writer.Write([]byte(s))
	return buff.Bytes()
}

type String string

func (s String) to866() []byte {
	buff := new(bytes.Buffer)
	writer := transform.NewWriter(buff, charmap.CodePage866.NewEncoder())
	defer writer.Close()
	writer.Write([]byte(string(s)))
	return buff.Bytes()
}

func ReceiveString(conn net.Conn) string {
	var size int32
	binary.Read(conn, binary.LittleEndian, &size)
	buff := make([]byte, size)
	conn.Read(buff)
	return from866(buff)
}

func SendString(conn net.Conn, s string) {
	size := int32(len(s))
	binary.Write(conn, binary.LittleEndian, size)
	conn.Write(to866(s))
}

func main() {
	if conn, err := net.Dial("tcp", "192.168.37.128:12345"); err != nil {
		log.Println("Server connection error")
	} else {
		defer conn.Close()
		for {
			var s string
			fmt.Scanln(&s)
			SendString(conn, s)
			fmt.Println(ReceiveString(conn))
		}
	}
}
